package com.zjdiepu.www.manage.api.base;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Add;
import com.zjdiepu.www.base.annotation.Update;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.ibiz.base.IBaseShortcutService;
import com.zjdiepu.www.ibiz.base.ISysPowerService;
import com.zjdiepu.www.model.base.dto.BaseShortcut;
import com.zjdiepu.www.model.base.dto.SysPower;
import com.zjdiepu.www.model.base.ext.BaseShortcutExt;
import com.zjdiepu.www.model.base.ext.SysPowerExt;
import com.zjdiepu.www.util.ExceptionHelper;

/**
 * 快捷方式管理Controller层<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年06月27日 17时33分<br/>
 * @since 1.0<br/>
 */
@RestController
@RequestMapping(value= "BaseShortcutController", produces="application/json;charset=UTF-8")
@Api(tags = {"快捷方式管理"}, produces="application/json;charset=UTF-8")
public class BaseShortcutController extends BaseController {
    @Resource
    private IBaseShortcutService baseShortcutService;
    @Resource
    private ISysPowerService sysPowerService;

    /**
     * @author xiongxiaotun <br/>
     * @Title: save  <br/>
     * @Description: 新增快捷方式管理 <br/>
     * @param baseShortcut
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "新增快捷方式管理", response = Boolean.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public ApiResponse save(@Validated(Add.class) @ModelAttribute BaseShortcut baseShortcut) {
    	AbstractSysUser currentUser = getCurrentUser();
    	baseShortcut.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	baseShortcut.setModifierName(currentUser.getName());
    	baseShortcut.setUserId(currentUser.getId());
        baseShortcutService.saveUpdateAndDelete(baseShortcut, OperateType.add);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: remove  <br/>
     * @Description: 删除快捷方式管理<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "删除快捷方式管理", response = Boolean.class, httpMethod="POST", tags={"删除"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "remove", method = RequestMethod.POST)
    public ApiResponse remove(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	baseShortcutService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.DELETED.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: disable  <br/>
     * @Description: 禁用快捷方式管理<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "禁用快捷方式管理", response = Boolean.class, httpMethod="POST", tags={"禁用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "disable", method = RequestMethod.POST)
    public ApiResponse disable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	baseShortcutService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.INVALID.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: enable <br/>
     * @Description: 启用快捷方式管理<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "启用快捷方式管理", response = Boolean.class, httpMethod="POST", tags={"启用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "enable", method = RequestMethod.POST)
    public ApiResponse enable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	baseShortcutService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.NORMAL.getCode(), ids);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: modify  <br/>
     * @Description: 修改快捷方式管理 <br/>
     * @param baseShortcut
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "修改快捷方式管理", response = Boolean.class, httpMethod="POST", tags={"修改"})
    @RequestMapping(value = "modify", method = RequestMethod.POST)
    public ApiResponse modify(@Validated(Update.class) @ModelAttribute BaseShortcut baseShortcut) {
    	AbstractSysUser currentUser = getCurrentUser();
    	baseShortcut.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	baseShortcut.setModifierName(currentUser.getName());
    	baseShortcut.setUserId(null);
    	baseShortcutService.saveUpdateAndDelete(baseShortcut, OperateType.edit);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: getById  <br/>
     * @Description: 主键查询快捷方式管理<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "主键查询快捷方式管理", response = BaseShortcut.class, httpMethod="POST", tags={"主键查询"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "getById", method = RequestMethod.POST)
    public ApiResponse getById(String id){
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
       BaseShortcut baseShortcut = baseShortcutService.selectById(id);
       if(null == baseShortcut) {
    	   return ApiResponse.fail(ResultFlagType.MISSING);
       }
       return ApiResponse.success(baseShortcut);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: list  <br/>
     * @Description: 条件查询快捷方式管理 <br/>
     * @param baseShortcutExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "条件查询快捷方式管理",response = BaseShortcut.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public ApiResponse list(@ModelAttribute BaseShortcutExt baseShortcutExt){
    	AbstractSysUser currentUser = getCurrentUser();
        baseShortcutExt.notDeleted();
        baseShortcutExt.setUserId(currentUser.getId());
        PageVo page = getPage(baseShortcutExt);
        int records = baseShortcutService.countByExt(baseShortcutExt);
        page.setRecords(records);
        if (records > 0) {
            List<BaseShortcut> baseShortcuts = baseShortcutService.selectByExt(baseShortcutExt);
            page.setRows(baseShortcuts);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: list  <br/>
     * @Description: 条件查询快捷方式管理 <br/>
     * @param baseShortcutExt
     * @return
     * @version V1.0  <br/>
     */
    @Deprecated
    @ApiOperation(value = "条件查询快捷方式管理",response = BaseShortcut.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "shorcutListOld", method = RequestMethod.POST)
    public ApiResponse shorcutListOld(@ModelAttribute BaseShortcutExt baseShortcutExt){
    	AbstractSysUser currentUser = getCurrentUser();
    	Boolean homePage = baseShortcutExt.getHomePage();
    	if(homePage != null && homePage) {
    		baseShortcutExt.setBaseWhere();
    		baseShortcutExt.setLimit(false);
    	} else {
    		baseShortcutExt.notDeleted();
    	}
        baseShortcutExt.setUserId(currentUser.getId());
        PageVo page = getPage(baseShortcutExt);
        int records = baseShortcutService.countMultiByExt(baseShortcutExt);
        page.setRecords(records);
        if (records > 0) {
            List<BaseShortcut> baseShortcuts = baseShortcutService.selectMultiByExt(baseShortcutExt);
            page.setRows(baseShortcuts);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: list  <br/>
     * @Description: 条件查询快捷方式管理 <br/>
     * @param baseShortcutExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "条件查询快捷方式管理",response = BaseShortcut.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "shorcutList", method = RequestMethod.POST)
    public ApiResponse shorcutList(@ModelAttribute BaseShortcutExt baseShortcutExt){
    	AbstractSysUser currentUser = getCurrentUser();
    	Boolean homePage = baseShortcutExt.getHomePage();
    	if(homePage != null && homePage) {
    		baseShortcutExt.setBaseWhere();
    		baseShortcutExt.setLimit(true);
    	} else {
    		baseShortcutExt.notDeleted();
    	}
    	String powerId = baseShortcutExt.getPowerId();
    	if(StringUtils.isNotBlank(powerId)) {
    		//查询所有权限，并过滤出该powerCode下的所有菜单ID
    		SysPowerExt sysPowerExt = new SysPowerExt();
    		sysPowerExt.setBaseWhere();
    		sysPowerExt.setMenuStatus(1); // 菜单
    		sysPowerExt.withOutPage();
    		List<SysPower> sysPowers = sysPowerService.selectByExt(sysPowerExt);
    		List<String> ids = CollectionInitUtil.emptyList();
    		filterIdsFromAllPowers(sysPowers, powerId, ids);
    		baseShortcutExt.setPowerIds(ids);
    		baseShortcutExt.setPowerId(null);
    	}
        baseShortcutExt.setUserId(currentUser.getId());
        PageVo page = getPage(baseShortcutExt);
        int records = baseShortcutService.countMultiByExt(baseShortcutExt);
        page.setRecords(records);
        if (records > 0) {
            List<BaseShortcut> baseShortcuts = baseShortcutService.selectMultiByExt(baseShortcutExt);
            page.setRows(baseShortcuts);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }
    
    /**
     * 过滤出当前模块的菜单ID
     * @param sysPowers
     * @param parentId 父级ID
     * @param ids  符合条件的ID
     */
    private void filterIdsFromAllPowers(List<SysPower> sysPowers,String parentId, List<String> ids){
    	if(null == ids) {
    		ExceptionHelper.thow(ResultFlagType.PARAM_EMPTY);
    	}
    	if(CollectionUtils.isEmpty(sysPowers)) {
    		return;
    	}
    	for(SysPower sysPower : sysPowers) {
    		String parentId_ = sysPower.getParentId();
    		if(StringUtils.isBlank(parentId_)) {
    			continue;
    		}
    		
    		String id = sysPower.getId();
    		if(StringUtils.isBlank(id)) {
    			continue;
    		}
    		
    		if(parentId.equals(parentId_)) {
    			if(sysPower.getQuick() == 1) { //href
    				ids.add(id);
    			} else { //click
    				filterIdsFromAllPowers(sysPowers, id, ids);
    			}
    		}
    	}
    }
}
